package com.minis.beans.factory.annotation;

import com.minis.BeansException;
import com.minis.beans.factory.BeanFactory;
import com.minis.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * 功能描述
 *
 * @author wanghongqian
 * @date 2023/10/17 17:10
 */
public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor {
    private BeanFactory beanFactory;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object result = bean;

        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if(fields != null){
            for(Field field:fields){
                boolean autowired = field.isAnnotationPresent(Autowired.class);
                if(autowired){
                    String fieldName = field.getName();
                    Object autowiredObj = this.beanFactory.getBean(fieldName);
                    try {
                        field.setAccessible(true);
                        field.set(bean,autowiredObj);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
}
